import { api } from '@/utils/request'

export interface WalletBalance {
  totalValue: number
  availableBalance: number
  immediateBalance: number
  frozenBalance: number
  lockedBalance: number
  totalRewardsValue: number
  cumulativeRewardsValue?: number
  cumulativeRewardsNear?: number
  freeHoldingNear: number
  currency: 'KRW' | 'USD'
  dayChange: number
  dayChangeRate: number
  nearPrice: number
  nearBalance: number
  nearStaked: number
  totalRewardsNear: number
  nearTotalValue: number
}

export interface InvestmentStats {
  totalInvestment: number
  currentValue: number
  totalReturn: number
  returnRate: number
  dayChange: number
  dayChangeRate: number
}

export interface NearAsset {
  symbol: string
  balance: number
  lockedAmount: number
  priceKRW: number
  totalValue: number
  change24h: number
  changeRate24h: number
}

export interface PortfolioDistribution {
  asset: string
  value: number
  percentage: number
  color: string
}

class WalletApiService {
  /**
   * 获取钱包概览信息
   */
  async getWalletBalance(): Promise<WalletBalance> {
    try {
      const response = await api.get<WalletBalance>('/api/wallet/overview')
      return response.data
    } catch (error) {
      console.error('지갑 개요 조회 실패:', error)
      // 返回默认数据而不是抛出错误，确保页面可用
      return {
        totalValue: 0,
        availableBalance: 0,
        immediateBalance: 0,
        frozenBalance: 0,
        lockedBalance: 0,
        totalRewardsValue: 0,
        freeHoldingNear: 0,
        currency: 'KRW' as const,
        dayChange: 0,
        dayChangeRate: 0,
        nearPrice: 0,
        nearBalance: 0,
        nearStaked: 0,
        totalRewardsNear: 0,
        nearTotalValue: 0
      }
    }
  }

  /**
   * 获取投资统计信息
   */
  async getInvestmentStats(): Promise<InvestmentStats> {
    try {
      const response = await api.get<InvestmentStats>('/api/wallet/investment')
      return response.data
    } catch (error) {
      console.error('투자 통계 조회 실패:', error)
      // 返回默认数据
      return {
        totalInvestment: 0,
        currentValue: 0,
        totalReturn: 0,
        returnRate: 0,
        dayChange: 0,
        dayChangeRate: 0
      }
    }
  }

  /**
   * 获取NEAR资产信息
   */
  async getNearAsset(): Promise<NearAsset> {
    try {
      const response = await api.get<NearAsset>('/api/wallet/assets')
      return response.data
    } catch (error) {
      console.error('NEAR 자산 조회 실패:', error)
      // 返回默认数据
      return {
        symbol: 'NEAR',
        balance: 0,
        lockedAmount: 0,
        priceKRW: 0,
        totalValue: 0,
        change24h: 0,
        changeRate24h: 0
      }
    }
  }

  /**
   * 获取投资组合分布
   */
  async getPortfolioDistribution(): Promise<PortfolioDistribution[]> {
    try {
      const response = await api.get<PortfolioDistribution[]>('/api/wallet/portfolio')
      return response.data
    } catch (error) {
      console.error('투자 포트폴리오 분포 조회 실패:', error)
      // 返回默认数据
      return [{
        asset: 'NEAR',
        value: 0,
        percentage: 100,
        color: '#9ca3af'
      }]
    }
  }

  /**
   * 带重试的获取钱包概览信息
   */
  async getWalletBalanceWithRetry(maxRetries: number = 2): Promise<{ data: WalletBalance; success: boolean }> {
    for (let attempt = 0; attempt <= maxRetries; attempt++) {
      try {
        const response = await api.get<WalletBalance>('/api/wallet/overview')
        return { data: response.data, success: true }
      } catch (error) {
        console.error(`지갑 개요 조회 실패 (시도 ${attempt + 1}/${maxRetries + 1}):`, error)
        if (attempt === maxRetries) {
          // 最后一次尝试失败，返回默认数据
          return {
            data: {
              totalValue: 0,
              availableBalance: 0,
              immediateBalance: 0,
              frozenBalance: 0,
              lockedBalance: 0,
              totalRewardsValue: 0,
              freeHoldingNear: 0,
              currency: 'KRW' as const,
              dayChange: 0,
              dayChangeRate: 0,
              nearPrice: 0,
              nearBalance: 0,
              nearStaked: 0,
              totalRewardsNear: 0,
              nearTotalValue: 0
            },
            success: false
          }
        }
        // 等待一秒后重试
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
    }
    // 这行代码理论上不会被执行到
    return {
      data: {
        totalValue: 0,
        availableBalance: 0,
        immediateBalance: 0,
        frozenBalance: 0,
        lockedBalance: 0,
        totalRewardsValue: 0,
        freeHoldingNear: 0,
        currency: 'KRW' as const,
        dayChange: 0,
        dayChangeRate: 0,
        nearPrice: 0,
        nearBalance: 0,
        nearStaked: 0,
        totalRewardsNear: 0,
        nearTotalValue: 0
      },
      success: false
    }
  }
}

export const walletApiService = new WalletApiService()
